package com.mge.humitureproj.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * Modbus RTU 协议工具类
 */
public class ModbusUtil {
    public static int calculateCRC(byte[] data) {
        int crc = 0xFFFF;
        for (byte b : data) {
            crc ^= (int) b & 0xFF;
            for (int i = 0; i < 8; i++) {
                if ((crc & 0x0001) != 0) {
                    crc >>= 1;
                    crc ^= 0xA001;
                } else {
                    crc >>= 1;
                }
            }
        }
        return crc;
    }

    /**
     * 验证 Modbus 响应的 CRC 校验值
     * @param data
     * @return
     */
    public static boolean verifyCRC(byte[] data) {
        if (data.length < 3) return false;

        // 提取接收到的 CRC（低字节在前）
        int receivedCrc = (data[data.length-2] & 0xFF) | ((data[data.length-1] & 0xFF) << 8);

        // 计算数据部分的 CRC
        byte[] dataWithoutCRC = Arrays.copyOf(data, data.length - 2);
        int calculatedCrc = calculateCRC(dataWithoutCRC);

        return receivedCrc == calculatedCrc;
    }

    /**
     * 解析 Modbus 读寄存器响应（功能码 03/04）
     */
    public static int[] parseReadRegistersResponse(byte[] data) {
        if (data.length < 5 || !verifyCRC(data)) {
            throw new IllegalArgumentException("无效的 Modbus 响应");
        }

        int functionCode = data[1] & 0xFF;
        if (functionCode != 0x03 && functionCode != 0x04) {
            throw new IllegalArgumentException("不支持的功能码: " + functionCode);
        }

        int byteCount = data[2] & 0xFF;
        int registerCount = byteCount / 2;
        int[] registers = new int[registerCount];

        for (int i = 0; i < registerCount; i++) {
            int highByte = data[3 + i*2] & 0xFF;
            int lowByte = data[4 + i*2] & 0xFF;
            registers[i] = (highByte << 8) | lowByte;
        }

        return registers;
    }


    /**
     * 构建 Modbus 读寄存器请求（功能码 03）
     */
    public static byte[] buildReadRegistersRequest(int slaveAddress, int startAddress, int quantity) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bos.write(slaveAddress & 0xFF);
        bos.write(0x03); // 功能码 03
        bos.write((startAddress >> 8) & 0xFF);
        bos.write(startAddress & 0xFF);
        bos.write((quantity >> 8) & 0xFF);
        bos.write(quantity & 0xFF);

        byte[] data = bos.toByteArray();
        int crc = calculateCRC(data);

        try {
            bos.write((crc & 0xFF));       // CRC 低字节
            bos.write(((crc >> 8) & 0xFF)); // CRC 高字节
            return bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("构建 Modbus 请求失败", e);
        }
    }

    // 获取本机ip地址
    public static String getLocalIp() throws IOException {
        String osName = System.getProperty("os.name").toLowerCase();
        Process process;
        if (osName.contains("linux")) {
            // Linux 系统命令
            String[] cmd = {"/bin/sh", "-c", "ifconfig | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}'"};
            process = Runtime.getRuntime().exec(cmd);
        } else if (osName.contains("windows")) {
            // Windows 系统命令（查找非 127.0.0.1 的 IPv4 地址）
            String[] cmd = {"cmd.exe", "/c", "for /f \"tokens=2 delims=:\" %a in ('ipconfig ^| findstr IPv4') do @echo %a"};
            process = Runtime.getRuntime().exec(cmd);
        } else {
            // 其他系统或未知环境
            return "127.0.0.1";
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String ip = line.trim();
                if (ip.contains(":")){
                    ip = ip.substring(ip.indexOf(":")+1);
                }
                if (!ip.equals("127.0.0.1") && !ip.isEmpty()) {
                    return ip;
                }
            }
        }

        return "127.0.0.1";
    }
}
